<template>
  <video 
    ref="videoRef"
    class="video-js" 
    controls
  />
</template>

<script setup lang="ts">
import 'video.js/dist/video-js.css'
import videojs from 'video.js'
defineOptions({
	name: 'Videojs',
})
const emit = defineEmits(['ready', 'play', 'pause', 'ended'])
const	props	=	defineProps({
  src: {
    type: String,
    default: ''
  },
  type: {
    type: String,
    default: 'video/mp4'
  },
})
const	videoRef = ref()
const playerRef = ref()
const init = () => {
  const source = {
    src: props.src,
    // type: 'application/x-mpegURL'
    type: props.type,
  }
  playerRef.value = videojs(videoRef.value, {
    techOrder: ['html5'],
    controls: true,
    autoplay: true,
    // 静音，默认是false，如果设置为true，视频播放时会自动静音
    // 为true则视频自动播放
    muted: true,
    preload: 'auto',
    // sources: [
    //   source,
    // ]
  })

  playerRef.value.src(source)
  playerRef.value.play()
  playerRef.value.on('ready', () => {
    console.log('视频加载完成,视频开始播放')
    emit('ready')
  })
  playerRef.value.on('pause', () => {
    console.log('视频暂停')
    emit('pause')
  })
  playerRef.value.on('play', () => {
    console.log('视频播放，快进或暂停后播放，会触发该事件')
    emit('play')
  })
  playerRef.value.on('ended', () => {
    console.log('视频播放结束')
    emit('ended')
  })
}
// 监听src变化,重新加载视频
watch(() => props.src, (val) => {
  if (val) {
    playerRef.value.src({
      src: props.src,
      // type: 'application/x-mpegURL',
      type: props.type,
    })
    playerRef.value.play()
  }
})

onMounted(() => {
  init()
})
</script>

<style lang="scss" scoped>
.video-js {
  width: 100%;
  height: 500px;
}
</style>
